package top.codef.gsonsupport;

import java.io.IOException;

import javax.money.MonetaryAmount;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import top.codef.money.interfaces.MercuryMonetaryAmountFormat;

public abstract class MoneyGsonAdapter<T extends MonetaryAmount> extends TypeAdapter<T> {

	private final MercuryMonetaryAmountFormat mercuryMonetaryAmountFormat;

	public MoneyGsonAdapter(MercuryMonetaryAmountFormat mercuryMonetaryAmountFormat) {
		this.mercuryMonetaryAmountFormat = mercuryMonetaryAmountFormat;
	}

	@Override
	public void write(JsonWriter out, T value) throws IOException {
		if (value == null)
			out.nullValue();
		else
			out.value(mercuryMonetaryAmountFormat.format(value));
	}

	@Override
	public T read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			in.nextNull();
			return null;
		}
		String moneyStr = in.nextString();
		return mercuryMonetaryAmountFormat.parse(moneyStr, getRawClass());
	}

	public abstract Class<T> getRawClass();

}
